package ui;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import model.Group;
import utils.DBUtil;

import java.util.ArrayList;
import java.util.List;

public class GroupListPage extends Application {

    private List<Group> groups = new ArrayList<>();
    private List<CheckBox> checkboxes = new ArrayList<>();
    private VBox vbox = new VBox();

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("分组管理");

        vbox.setPadding(new Insets(10));
        vbox.setSpacing(10);
        vbox.getStyleClass().add("root");

        // 创建全选复选框
        CheckBox selectAllCheckBox = new CheckBox("全选");
        selectAllCheckBox.setOnAction(e -> toggleAllGroups(selectAllCheckBox.isSelected()));
        selectAllCheckBox.getStyleClass().add("select-all-checkbox");

        // 创建添加分组按钮
        Button addButton = new Button("添加分组");
        addButton.setPrefWidth(100);
        addButton.setPrefHeight(40);
        addButton.setOnAction(e -> showCreateGroupDialog());
        addButton.getStyleClass().add("add-button");

        // 创建删除分组按钮
        Button deleteButton = new Button("删除分组");
        deleteButton.setOnAction(e -> deleteSelectedGroups());
        deleteButton.setPrefWidth(100);
        deleteButton.setPrefHeight(40);
        deleteButton.getStyleClass().add("delete-button");

        // 创建返回按钮
        Button backButton = new Button("返回菜单");
        backButton.setPrefWidth(100);
        backButton.setPrefHeight(40);
        backButton.setOnAction(e -> goBackToMenuPage(primaryStage));
        backButton.getStyleClass().add("back-button");

        // 创建底部的HBox用于按钮布局
        HBox buttonContainer = new HBox(10, selectAllCheckBox, addButton, deleteButton, backButton);
        buttonContainer.setAlignment(Pos.CENTER_LEFT);
        buttonContainer.setPadding(new Insets(10));
        buttonContainer.getStyleClass().add("button-container");

        // 加载并展示分组列表
        loadGroupList(vbox, primaryStage);

        ScrollPane scrollPane = new ScrollPane(vbox);
        scrollPane.setFitToWidth(true);
        scrollPane.getStyleClass().add("scroll-pane");

        VBox root = new VBox(scrollPane, buttonContainer);
        root.setSpacing(10);
        root.setPadding(new Insets(10));
        root.getStyleClass().add("root");

        Scene scene = new Scene(root, 1000, 900);
        scene.getStylesheets().add(getClass().getResource("/css/logisticsList.css").toExternalForm());

        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void loadGroupList(VBox vbox, Stage primaryStage) {
        vbox.getChildren().clear();
        checkboxes.clear();

        groups = DBUtil.selectAllGroups();

        for (Group group : groups) {
            HBox row = new HBox(10);

            row.getStyleClass().add("hbox");

            CheckBox checkBox = new CheckBox();
            checkboxes.add(checkBox);

            Label nameLabel = new Label(group.getName());
            HBox.setHgrow(nameLabel, Priority.ALWAYS);
            nameLabel.setMaxWidth(Double.MAX_VALUE);
            nameLabel.getStyleClass().add("label");

            Button detailButton = new Button("详情");
            detailButton.setOnAction(e -> showGroupDetail(primaryStage,group));
            detailButton.getStyleClass().add("button");

            row.getChildren().addAll(checkBox, nameLabel, detailButton);
            vbox.getChildren().add(row);
        }
    }

    private void deleteSelectedGroups() {
        List<Group> groupsToDelete = new ArrayList<>();

        for (int i = 0; i < checkboxes.size(); i++) {
            if (checkboxes.get(i).isSelected()) {
                groupsToDelete.add(groups.get(i));
            }
        }

        for (Group group : groupsToDelete) {
            DBUtil.deleteGroup(group.getId());
        }

        loadGroupList(vbox, null);
    }

    private void showCreateGroupDialog() {
        TextInputDialog dialog = new TextInputDialog();
        dialog.setTitle("创建新分组");
        dialog.setHeaderText(null);
        dialog.setContentText("请输入分组名称:");

        dialog.showAndWait().ifPresent(groupName -> {
            if (!groupName.trim().isEmpty()) {
                Group newGroup = new Group(0, groupName);
                DBUtil.insertGroup(newGroup);
                loadGroupList(vbox, null);
            } else {
                showAlert("错误", "分组名称不能为空", Alert.AlertType.ERROR);
            }
        });
    }

    private void showGroupDetail(Stage primaryStage,Group group) {
        GroupDetailPage groupDetailPage = new GroupDetailPage(group.getId());

        try {
            primaryStage.close();
            groupDetailPage.start(new Stage());
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    private void goBackToMenuPage(Stage currentStage) {
        MenuPage menuPage = new MenuPage(); // 假设 MenuPage 是你的菜单页面类
        try {
            menuPage.start(new Stage());
            currentStage.close(); // 关闭当前的 GroupManagementPage 窗口
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    private void toggleAllGroups(boolean selectAll) {
        for (CheckBox checkBox : checkboxes) {
            checkBox.setSelected(selectAll);
        }
    }

    private void showAlert(String title, String message, Alert.AlertType alertType) {
        Alert alert = new Alert(alertType);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }


}
